#!/usr/bin/env python3.8
# -*- encoding: utf-8 -*-
'''
@File    :   models.py
@Time    :   2021/10/09 15:24:07
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
from app.ext import db
from datetime import datetime
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask import current_app
from flask_avatars import Identicon
class Role(db.Model):
    __tablename__ = 'role'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))
    #创建一个关联
    users = db.relationship('User', backref='role', lazy='dynamic')

    def __repr__(self):
        return '<Role %s>' % self.name


# User类继承自db.Model
class User(db.Model,UserMixin): 
    #定义表名
    __tablename__ = 'users'
    # 定义id，并且为主键
    id = db.Column(db.Integer, primary_key=True)  
    #用户名
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    #真实名称
    real_name = db.Column(db.String(64))
    #设置hash密码
    password_hash = db.Column(db.String(256))
    about_me = db.Column(db.Text)
    last_seen = db.Column(db.DateTime, default=datetime.utcnow)
    #关联角色模型的外键
    role_id = db.Column(db.Integer, db.ForeignKey('role.id'))
    confirmed = db.Column(db.Boolean, default=False)
    gender = db.Column(db.String(64))
    site = db.Column(db.String(256))
    #头像相关信息
    avatar_s = db.Column(db.String(128))
    avatar_m = db.Column(db.String(128))
    avatar_l = db.Column(db.String(128))
    raw_avatar = db.Column(db.String(128))
    
    # def __init__(self):
    #     self.generate_avatar()
    
    #定义User类的返回名称
    def __repr__(self):  
        #返回 <User 用户名>
        return '<User %s>' % self.username

    @property
    def password(self, password):
        raise AttributeError("password属性不能直接访问")

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    #生成验证的token
    def generate_confirmation_token(self, expiration=3600):
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'confirm': self.id}).decode('utf-8')

    def confirm(self, token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token.encode('utf-8'))
        except:
            return False
        if data.get('confirm') != self.id:
            return False
        self.confirmed = True
        db.session.add(self)
        return True

    def generate_avatar(self):
        avatar = Identicon()
        filenames = avatar.generate(text=self.username)
        self.avatar_s = filenames[0]
        self.avatar_m = filenames[1]
        self.avatar_l = filenames[2]
        db.session.commit()
    

